package br.com.cast.syscast.uf.paginas;

import org.apache.wicket.markup.html.form.ChoiceRenderer;
import org.apache.wicket.markup.html.form.DropDownChoice;
import org.apache.wicket.markup.html.form.Form;
import org.apache.wicket.markup.html.form.IChoiceRenderer;
import org.apache.wicket.markup.html.form.RequiredTextField;
import org.apache.wicket.markup.html.link.Link;
import org.apache.wicket.model.CompoundPropertyModel;
import org.apache.wicket.spring.injection.annot.SpringBean;
import org.apache.wicket.validation.validator.StringValidator;

import br.com.cast.syscast.HomePage;
import br.com.cast.syscast.excecoes.PaisJaCadastrado;
import br.com.cast.syscast.excecoes.UfJaCadastrada;
import br.com.cast.syscast.models.Pais;
import br.com.cast.syscast.models.Uf;
import br.com.cast.syscast.services.PaisService;
import br.com.cast.syscast.services.UfService;
import br.com.cast.syscast.util.ComponentUtil;

public class FormUf extends Form<Uf> {

	private static final long serialVersionUID = 1L;

	@SpringBean
	private UfService ufService;

	@SpringBean
	private PaisService paisService;

	public FormUf(String id) {
		super(id, new CompoundPropertyModel<Uf>(new Uf()));

		criaCampoPais();
		
		criaCampoSigla();
		
		criaCampoNome();

		criaLinkCancelar();
	}

	private void criaCampoNome() {
		add(new RequiredTextField<>("nome")
				.add(new StringValidator(0, 50)));
	}

	private void criaCampoSigla() {
		add(new RequiredTextField<>("sigla")
			.add(new StringValidator(0, 2)));
	}

	private void criaCampoPais() {
		IChoiceRenderer<Pais> renderer = new ChoiceRenderer<>("nome");
		add(new DropDownChoice<>(
				"pais", paisService.consultaTodos(), renderer));
	}

	private void criaLinkCancelar() {
		add(new Link("cancelar") {
			@Override
			public void onClick() {
				redirecionaListar();
			}
		});
	}

	@Override
	protected void onSubmit() {
		Uf uf = (Uf) getDefaultModelObject();

		try {
			ufService.salvar(uf);
			HomePage template = redirecionaListar();
			template.success("Registro inserido com sucesso!");
		} catch (UfJaCadastrada e) {
			error(e.getMessage());
		}
	}

	private HomePage redirecionaListar() {
		HomePage template = ComponentUtil.getTemplate(this);
		template.replace(new ListarUf(HomePage.ID_CONTEUDO));
		return template;
	}

}
